import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/conversation/groupMessagesPage.dart';
import 'package:flutter/material.dart';

import '../constants.dart' show AppColors, AppStyles, Constants, Routes;
import '../modal/conversation.dart'
    show Conversation, Device, ConversationPageData;
import 'package:intl/intl.dart';
import '../cmomon/global.dart' as GlobalData;
import '../cmomon/conversationList.dart';
import '../cmomon/usersModel.dart';
import 'package:provider/provider.dart';
import '../models/index.dart';
import '../conversation/messagesPage.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'package:async/async.dart';

final DateFormat formatter = new DateFormat('HH:mm');

class _ConversationItem extends StatelessWidget {
  final Function refreshConversationList;
  static const VERTICAL_PADDING = 12.0;
  static const HORIZONTAL_PADDING = 18.0;
  static const UN_READ_MSG_CIRCLE_SIZE = 20.0;
  static const UN_READ_MSG_DOT_SIZE = 12.0;

  _ConversationItem(
      {Key key,
      this.conversation,
      this.tapPos,
      @required this.refreshConversationList})
      : assert(conversation != null),
        super(key: key);

  final Conversation conversation;
  var tapPos;

  _showMenu(BuildContext context, Offset tapPos) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject();
    final RelativeRect position = RelativeRect.fromLTRB(tapPos.dx, tapPos.dy,
        overlay.size.width - tapPos.dx, overlay.size.height - tapPos.dy);
    showMenu<String>(
        context: context,
        position: position,
        items: <PopupMenuItem<String>>[
          PopupMenuItem(
            child: Text(Constants.MENU_MARK_AS_UNREAD_VALUE),
            value: Constants.MENU_MARK_AS_UNREAD,
          ),
          PopupMenuItem(
            child: Text(Constants.MENU_PIN_TO_TOP_VALUE),
            value: Constants.MENU_PIN_TO_TOP,
          ),
          PopupMenuItem(
            child: Text(Constants.MENU_DELETE_CONVERSATION_VALUE),
            value: Constants.MENU_DELETE_CONVERSATION,
          ),
        ]).then<String>((String selected) {
      switch (selected) {
        default:
          print('当前选中的是：$selected');
      }
    });
  }

  bool _isAvatarFromNet(avatar) {
    if (avatar.indexOf('http') == 0 || avatar.indexOf('https') == 0) {
      return true;
    }
    return false;
  }

  Widget getAvatarWidget(User user) {
    String avatarStr;
    if (user.portrait != null && user.portrait.length > 0) {
      avatarStr = user.portrait;
    } else {
      avatarStr = 'assets/images/default_nor_avatar.png';
    }

    Widget avatar;
    if (_isAvatarFromNet(avatarStr)) {
      avatar = Image.network(
        avatarStr,
        width: Constants.ConversationAvatarSize,
        height: Constants.ConversationAvatarSize,
        fit: BoxFit.cover,
      );
    } else {
      avatar = Image.asset(
        avatarStr,
        width: Constants.ConversationAvatarSize,
        height: Constants.ConversationAvatarSize,
        fit: BoxFit.cover,
      );
    }
    return avatar;
  }

  final AsyncMemoizer _memoizer = AsyncMemoizer();

  getOtherSideInfo() {
    return _memoizer.runOnce(() async {
      if (conversation.type == 'Single') {
        String userId = conversation.otherSideUserId;
        Map result = await FlutterWildfire.getUserInfo(userId, true);
        User user = User.fromJson(result);
        return user;
      } 
      if (conversation.type == 'Group') {
        String groupId = conversation.otherSideUserId;
        Map result = await FlutterWildfire.getGroupInfo(groupId);
        Group group = Group.fromJson(result);
        return group;
        // User user = User.fromJson(result);
        // return user;
      } 
      print('未知的会话类型 conversation.type');
    });
  }

  @override
  Widget build(BuildContext context) {
    print(conversation);
    return FutureBuilder(
      future: getOtherSideInfo(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          // 根据图片的获取方式初始化头像组件
          User user;
          Widget avatar;
          String displayName;
          Group group;
          if (snapshot.data is User) {
            user = snapshot.data;
            avatar = myAvatar(user.portrait);
            displayName = user.displayName;
          }
          if (snapshot.data is Group) {
            group = snapshot.data;
            avatar = myAvatar(group.portrait);
            displayName = group.name;
            
          }

          avatar = ClipRRect(
            borderRadius: BorderRadius.circular(Constants.AvatarRadius),
            child: avatar,
          );

          Widget avatarContainer;
          if (conversation.unreadMsgCount > 0) {
            // 未读消息角标
            Widget unreadMsgCountText;
            if (conversation.displayDot) {
              unreadMsgCountText = Container(
                width: UN_READ_MSG_DOT_SIZE,
                height: UN_READ_MSG_DOT_SIZE,
                decoration: BoxDecoration(
                  borderRadius:
                      BorderRadius.circular(UN_READ_MSG_DOT_SIZE / 2.0),
                  color: Color(AppColors.NotifyDotBg),
                ),
              );
            } else {
              unreadMsgCountText = Container(
                width: UN_READ_MSG_CIRCLE_SIZE,
                height: UN_READ_MSG_CIRCLE_SIZE,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius:
                      BorderRadius.circular(UN_READ_MSG_CIRCLE_SIZE / 2.0),
                  color: Color(AppColors.NotifyDotBg),
                ),
                child: Text(conversation.unreadMsgCount.toString(),
                    style: AppStyles.UnreadMsgCountDotStyle),
              );
            }

            avatarContainer = Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                avatar,
                Positioned(
                  right: conversation.displayDot ? -4.0 : -6.0,
                  top: conversation.displayDot ? -4.0 : -6.0,
                  child: unreadMsgCountText,
                )
              ],
            );
          } else {
            avatarContainer = avatar;
          }

          // 勿扰模式图标
          var _rightArea = <Widget>[
            Text(conversation.updateAt, style: AppStyles.DesStyle),
            SizedBox(height: 10.0),
          ];
          if (conversation.isMute) {
            _rightArea.add(Icon(
                IconData(
                  0xe755,
                  fontFamily: Constants.IconFontFamily,
                ),
                color: Color(AppColors.ConversationMuteIcon),
                size: Constants.ConversationMuteIconSize));
          } else {
            _rightArea.add(Icon(
                IconData(
                  0xe755,
                  fontFamily: Constants.IconFontFamily,
                ),
                color: Colors.transparent,
                size: Constants.ConversationMuteIconSize));
          }

          return Material(
            color: Color(AppColors.ConversationItemBg),
            child: InkWell(
              onTap: () async {
                GlobalData.Global.isReFetchWhenReseveMessage = false;
                var result = await Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                      if (snapshot.data is User) {
                        return MessagesPage(user: user);
                      } else {
                        print('打开会话：${conversation.title}');
                        return GroupMessagesPage(groupInfo: group);
                      }
                }));
                try {
                  GlobalData.Global.isReFetchWhenReseveMessage = true;
                  this.refreshConversationList();
                  // TODO: 这里如果先清除再刷新就会刷新失败
                  await FlutterWildfire.clearUnreadStatus(
                      'Single', user.uid, 0);
                } catch (e) {
                  print('出错了');
                  print(e);
                }
              },
              onTapDown: (TapDownDetails details) {
                tapPos = details.globalPosition;
              },
              onLongPress: () {
                _showMenu(context, tapPos);
              },
              child: Container(
                padding: const EdgeInsets.only(left: HORIZONTAL_PADDING),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    avatarContainer,
                    Container(width: 12.0),
                    Expanded(
                        child: Container(
                      padding: const EdgeInsets.only(
                          right: HORIZONTAL_PADDING,
                          top: VERTICAL_PADDING,
                          bottom: VERTICAL_PADDING),
                      decoration: BoxDecoration(
                          border: Border(
                        bottom: BorderSide(
                            width: Constants.DividerWidth,
                            color: Color(AppColors.DividerColor)),
                      )),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(displayName,
                                    style: AppStyles.TitleStyle),
                                SizedBox(height: 2.0),
                                Text(conversation.des,
                                    style: AppStyles.DesStyle, maxLines: 1)
                              ],
                            ),
                          ),
                          Container(width: 10.0),
                          Column(
                            children: _rightArea,
                          ),
                        ],
                      ),
                    )),
                  ],
                ),
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}

class ConversationPage extends StatelessWidget {
  final Function refreshConversationList;
  ConversationPage({@required this.refreshConversationList});
  @override
  Widget build(BuildContext context) {
    return Consumer2<ConversationModel, UsersModel>(
      builder:
          (BuildContext context, conversationModel, usersModel, Widget child) {
        return Container(
          color: const Color(AppColors.BackgroundColor),
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              var data = conversationModel.list[index];
              String formatted = formatter.format(
                  DateTime.fromMillisecondsSinceEpoch(data['timestamp']));
              if (data['lastMessage'] == null) {
                return Container();
              }
              String type = data['lastMessage']["conversation"]['type'];
              bool isGroup = type == 'Group';
              var content = data['lastMessage']['content'];
              String contentStr;
              if (content["tip"] != null) {
                contentStr = content["tip"];
              } else if (content["content"] is String) {
                contentStr = content["content"];
              } else if (content["audioOnly"] == false &&
                  content["callId"] != null) {
                contentStr = '[视频通话]';
                print(data);
              } else if (isGroup) {

                contentStr = (content['fromSelf'] ? '您创建了群组 ' : '${content['creator']}创建了群组 ') + content['groupName'];
              } else {
                switch (content['mediaType']) {
                  case 'IMAGE':
                    contentStr = '[图片]';
                    break;
                  case 'FILE':
                    contentStr = '[动态表情]';
                    print(data);
                    break;
                  case 'StickerMessageContent':
                    print(data);
                    contentStr = '[表情]';
                    break;
                  case 'VOICE':
                    contentStr = '[语音]';
                    break;
                  default:
                    print('[未知类型]');
                    print(data);
                    contentStr = '[未知类型]';
                }
              }
              String otherSideUserId = data["conversation"]["target"];

              return _ConversationItem(
                  refreshConversationList: this.refreshConversationList,
                  conversation: Conversation(
                      type: data["conversation"]['type'],
                      des: contentStr,
                      isMute: false,
                      unreadMsgCount: data["unreadCount"]["unread"],
                      updateAt: formatted,
                      otherSideUserId: otherSideUserId,
                      title: otherSideUserId,
                      avatar: 'assets/images/default_nor_avatar.png'));
            },
            itemCount: conversationModel.list.length,
          ),
        );
      },
    );
  }
}
